<template>
    <div class="login background-general">
        <div class="logo"></div>
        <div class="login-box">
            <div class="login-form col col-5">
                <ul>
                    <li :class="{active:tabView==1}" @click="tabView=1">个人登录</li>
                    <li :class="{active:tabView==2}" @click="tabView=2">企业登录</li>
                </ul>
                <!-- 个人登录 -->
                <div v-if="tabView==1" class="div-form user-login">
                    <p class="text-center">欢迎来到<span>GLP</span>游戏化学习平台</p>
                    <div class="error-box" :class="{active:user.error}">{{user.errorMessage}}</div>
                    <div class="form-group">
                        <div class="icon-box">
                            <img src="../../static/image/icon-account.png">
                        </div>
                        <!-- <input v-model.trim="user.mobile" type="text" > -->
                        <input v-model.trim="user.mobile" type="text" @blur="validateTel()">
                    </div>
                    <div class="form-group">
                        <div class="icon-box">
                            <img src="../../static/image/icon-password.png">
                        </div>
                        <!-- <input v-model.trim="user.password" type="password" @keyup.enter="userLogin" @blur="test"> -->
                        <input v-model.trim="user.password" type="password" @keyup.enter="userLogin" @blur="validatePwd()">
                    </div>
                    <div class="assist-box">
                      <div @click="userAutologin" class="fl">
                        <img :src="'../../static/image/icon-'+(user.autoLogin?'':'un')+'selected.png'" alt="">
                        下次自动登录
                      </div>
                      <div class="fr">
                          <router-link to="forgetPassword">忘记密码？</router-link>
                          
                      </div>
                    </div>
                    <!-- <router-link to="home" class="btn-login">登录</router-link> -->
                    <button class="btn-login clear" @click="userLogin()">登录</button>
                    <!--<a class="no-account" href="">没有账号？个人注册</a>-->
                </div>
                <!-- 个人登录 end-->
                <!-- 企业登录 -->
                <div v-if="tabView==2" class="div-form corp-login">
                    <p class="text-center">欢迎来到<span>GLP</span>游戏化学习平台</p>
                    <!-- <div class="error-box" :class="{active:corp.error}">{{corp.errorMessage}}</div> -->
                    <div class="error-box" :class="{active:corp.error}">{{corp.errorMessage}}</div>
                    <div class="form-group">
                        <div class="icon-box">
                            <img src="../../static/image/icon-account.png">
                        </div>
                        <!-- <input v-model.trim="corp.email" type="email"> -->
                        <input v-model.trim="corp.email" type="email" @blur="validateCom()">
                    </div>
                    <div class="form-group">
                        <div class="icon-box">
                            <img src="../../static/image/icon-password.png">
                        </div>
                        <!-- <input v-model.trim="corp.password" type="password" @keyup.enter="adminLogin" > -->
                        <input v-model.trim="corp.password" type="password" @keyup.enter="adminLogin" @blur="validateCP()">
                    </div>
                    <div class="assist-box">
                        <div @click="corpAutologin" class="f1">
                            <img :src="'../../static/image/icon-'+(corp.autoLogin?'':'un')+'selected.png'" alt="">
                            下次自动登录
                        </div>
                        <div class="fr">
                          <router-link to="businessForgetpassword">忘记密码？</router-link>
                          
                      </div>
                    </div>
                    <!-- <router-link to="adminHome" class="btn-login" >登录</router-link> -->
                    <button class="btn-login" @click="adminLogin()">登录</button>
                    <!--<a class="no-account" href="">没有账号？企业注册</a>-->
                </div>
                <!-- 企业登录 end-->
            </div>
            <div class="login-welcome col col-5" :class="[tabView==1?'picture-box-1':'picture-box-2']">
                <p class="text-center">
                    <span>Welcome</span><br>
                    <i>Sign in to discover the <br>New Learning</i>
                </p>
            </div>
        </div>
        <copyright></copyright>
    </div>
</template>
<script type="text/javascript">
    import copyright from '../components/copyright.vue';

	export default{
		components: {copyright},
		data(){
			return{
                tabView: 1,
                userBtn:true,
                adminBtn:true,
                // 个人
                user: {
                    mobile: '',
                    password: '',
                    autoLogin: false,
                    error: false,
                    errorMessage: ''
                },
                // 企业 
                corp: {
                    email: '',
                    password: '',
                    autoLogin: false,
                    error: false,
                    errorMessage: ''
                }
                
			}
		},
		methods: {
            // 学员登录
            userLogin(){
                let _this=this;
                let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
                // let reg = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
                // 非空验证
                if(this.user.mobile == "" || this.user.password == ""){
                    this.user.errorMessage = "账号密码不能为空！"
                    this.user.error = true;
                    // this.$message({
                    //     message:"账号密码不能为空！",
                    //     type:'warning'
                    // });
                    return
                }else{
                    this.user.errorMessage = ""
                    this.user.error = false
                };
                // 号码正则验证
                if(!reg.test(this.user.mobile)){
                    this.user.errorMessage = "手机号码格式错误"
                    this.user.error = 'true'
                //    this.$message({
                //         message:"手机号码格式错误",
                //         type:'warning'
                //     });
                    return
                };
                // 是否自动登录  true则调用配置cookie方法
                if(this.user.autoLogin == true) {
                    //传入账号名，密码，和保存天数3个参数
                    this.setCookie(this.user.mobile,this.user.password,7);
                };

                let data={
                    mobile:this.user.mobile,
                    password:md5(this.user.password)
                };
                console.log(data)
                this.$http.studentLogin(data,res=>{
                    // 存储session
                    sessionStorage.setItem("login",JSON.stringify(res.data));
                    // 存储localStorage
                    // localStorage.setItem("login",JSON.stringify(res.data));   
                    
                    console.log(res);           
                    //this.userBtn=false;
                    this.user.error = false;
                    this.$message({
                        message:"登陆成功！",
                        type:"success",
                        
                        onClose:()=>{
                              _this.$router.push({name:"home"});
                        }
                    })
                },err=>{
                    this.userBtn=true;                    
                    console.log(err);
                    this.user.error = true;
                    this.user.errorMessage = err.message;
                    
                    // this.$message({
                    //     message:err.message,
                    //     type:'warning'
                    // });
                });
                
            },

            // 管理员登录
            adminLogin(){
                let _this=this;
                if(this.corp.email=="" || this.corp.password==""){
                    this.corp.errorMessage = '账号密码不能为空',
                    this.corp.error = true;
                    // this.$message({
                    //     message:"请检查账号或密码！",
                    //     type:'warning'
                    // });
                    return
                };
                // 是否自动登录  true则调用配置cookie方法
                if(this.corp.autoLogin == true) {
                    //传入账号名，密码，和保存天数3个参数
                    this.setCookie(this.corp.email,this.corp.password,7);
                };
				let data={
					email:this.corp.email,
					password:md5(this.corp.password),
					//password:this.corp.password,
                };
                console.log(data)
                this.$http.adminLogin(data,(successRes) => {
                    console.log(successRes);
                    // 存储session
                    sessionStorage.setItem("login",JSON.stringify(successRes.data));
                    //this.adminBtn=false;
                    this.corp.error = false;
                    this.$message({
                        message: '登陆成功！',
                        type: 'success',
                        onClose:()=>{
                             _this.$router.push({name:"adminHome"});
                        }
                    })
                    // this.$message({
                    //     message:"登陆成功！",
                    //     type:"success",
                    //     onClose:()=>{
                    //          _this.$router.push({name:"adminHome"});
                    //     }
                    // })
                }, (errorRes) => {
                    this.adminBtn=true;                    
                    console.log(errorRes);
                    this.corp.error = true;
                    this.corp.errorMessage = errorRes.message;
                    // this.$message({
                    //     message:err.message,
                    //     type:'warning'
                    // });
                });
            },
			//corpLogin(){},
			contetnCenter(){
				let windowHeight=$(window).height();
				let centerHeight=$(".contetn-center").height();
				if(windowHeight>centerHeight && windowHeight>545){
					$(".contetn-center").css("margin-top",(windowHeight-centerHeight)/2-90)
				}else{
					$(".contetn-center").css("margin-top","0")
				}
            },
            // 个人登录失去焦点验证(手机)
            validateTel(){
                let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
                // 非空验证
                if(this.user.mobile==""){
                     this.user.errorMessage = '账号不能为空！';
                      this.user.error = true;
                    return
                }
                // 号码正则验证
                if(!reg.test(this.user.mobile)){
                    this.user.errorMessage = '手机号码格式错误';
                    this.user.error = true;
                    return
                }else{
                    this.user.error = false;
                }
            },
            // 个人登录失去焦点验证(密码)
            validatePwd(){
                // 非空验证
                if(this.user.password==''){
                     this.user.errorMessage = '密码不能为空！';
                      this.user.error = true;
                    return
                }else{
                    this.user.error = false;
                }
            },
            // 企业失去焦点验证（邮箱）
            validateCom(){
                // 非空验证
                if(this.corp.email==""){
                    this.corp.errorMessage = '邮箱不能为空',
                    this.corp.error = true;
                    return
                }else{
                    this.corp.error = false;
                    };
            },
            // 企业失去焦点验证（密码）
            validateCP(){
                if(this.corp.password==""){
                    this.corp.errorMessage = '密码不能为空',
                    this.corp.error = true;
                    return
                }else{
                    this.corp.error = false;
                }
            },
            // md5加密
            // getmd5(){
                userAutologin:function(){
                    this.user.autoLogin=!this.user.autoLogin
                    if (this.user.autoLogin==false){
                        this.clearCookie();
                    }
                },
                corpAutologin:function(){
                    this.corp.autoLogin=!this.corp.autoLogin
                    if (this.corp.autoLogin==false){
                        this.clearCookie();
                    }
                },
            // },
            //设置cookie
            setCookie(account,password,exdays) {
                var exdate=new Date();//获取时间
                exdate.setTime(exdate.getTime() + 24*60*60*1000*exdays);//保存的天数
                //字符串拼接cookie
                if (this.tabView === 1) {
                    window.document.cookie="mobile"+ "=" +account+";path=/;expires="+exdate.toGMTString();//手机号
                    window.document.cookie="password"+"="+password+";path=/;expires="+exdate.toGMTString();// 个人密码
                } else if(this.tabView === 2) {
                    window.document.cookie="email"+ "=" +account+";path=/;expires="+exdate.toGMTString();// 邮箱
                    window.document.cookie="cpassword"+"="+password+";path=/;expires="+exdate.toGMTString();// 企业密码
                }
                
                
            },
            //读取cookie
            getCookie:function () {
                if (document.cookie.length>0) { 
                    var arr=document.cookie.split('; ');//这里显示的格式需要切割一下自己可输出看下
                    for(var i=0;i<arr.length;i++){  
                        var arr2=arr[i].split('=');//再次切割
                        //判断查找相对应的值
                        if (this.tabView ==1) {
                            if(arr2[0]=='mobile'){
                                this.user.autoLogin = true;
                                //保存到保存数据的地方
                                this.user.mobile=arr2[1]; // 手机号
                            }else if(arr2[0]=='password'){
                                this.user.password=arr2[1]; // 个人密码
                            }
                            
                        } else if (this.tabView ==2) {
                            if(arr2[0] == 'email'){
                                this.corp.autoLogin = true
                                this.corp.email=arr2[1];// 邮箱
                            }else if(arr2[0] == 'cpassword'){
                                this.corp.password=arr2[1]// 企业密码
                            }
                            
                        }
                    }
                }
            },
            //清除cookie
            clearCookie:function () {
                this.setCookie("","",-1);//修改2值都为空，天数为负1天就好了
            },
            test(){
                alert(11)
                if(this.user.mobile !='' && this.user.password) {
                    // alert('提示消失了');
                    this.user.error = false;
                }
            }



        },
        
		created(){//页面加载之前
			$(window).resize(()=>{
				this.contetnCenter();
			});
        },
        watch:{
            tabView(){
                this.getCookie();
            }
            
        },
		mounted(){
            //页面加载完之后
            this.contetnCenter();

            //页面加载调用获取cookie值
            this.getCookie()
           
		}
	}
</script>